package com.itjiange.dao.impl;

import com.itjiange.dao.UserDao;
import com.itjiange.pojo.User;
import com.itjiange.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

import static com.itjiange.constant.LoggerConstant.logger;

/**
 * 用户数据层实现类
 *
 * @author ItJiange
 * @date 2023/10/21
 */
public class UserDaoImpl implements UserDao {
    private static final QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());

    /**
     * 根据用户名查询数据
     *
     * @param username
     */
    @Override
    public User selectByUserName(String username) {
        // 定义 sql
        String sql = "select * from kfm_user where username = ?;";
        // 执行查询
        try {
            return queryRunner.query(sql, new BeanHandler<>(User.class), username);
        } catch (SQLException e) {
            e.printStackTrace();
            logger.info("sql 执行错误");
            return null;
        }
    }

    /**
     * 根据用户名和密码查询数据
     *
     * @param username
     * @param userPassword
     * @return
     */
    @Override
    public User getByNameAndPassword(String username, String userPassword) {
        // 定义 sql
        String sql = "select * from kfm_user where username = ? and password = ?;";
        // 执行查询
        try {
            return queryRunner.query(sql, new BeanHandler<>(User.class), username, userPassword);
        } catch (SQLException e) {
            e.printStackTrace();
            logger.info("sql 执行错误");
            return null;
        }
    }

    /**
     * 插入用户数据
     *
     * @param username
     * @param userPassword
     * @param email
     * @return
     */
    @Override
    public int insertUser(String username, String userPassword, String email) {
        // 定义 sql
        String sql = "insert into kfm_user (username, password, email) values (?, ?, ?);";
        try {
            User insert = queryRunner.insert(sql, new BeanHandler<>(User.class), username, userPassword, email);
            return insert != null ? 1 : -1;
        } catch (SQLException e) {
            e.printStackTrace();
            logger.info("sql 执行错误");
            return -1;
        }
    }
}
